from airtest.aircv import *
from airtest.core.api import *
from PIL import Image
import pytesseract
from comtypes.gen._00020430_0000_0000_C000_000000000046_0_2_0 import Picture

#连接窗口
dev = connect_device("windows:///")
try:
     dev = connect_device("windows:///?title_re=.*Cregis*")
except:
    start_app(r"C:\Users\Administrator\AppData\Local\Programs\CregisTest\CregisTest_3.4.0\CregisTest.exe")
    sleep(2)
    dev = connect_device(r"windows:///?title_re=.*Cregis*")
sleep(1)

# 1. 获取当前设备的截图对象（兼容旧版本）
img = dev.snapshot()  # 直接调用设备的截图方法，返回图片对象
sna = crop_image(img, (142,239,857,475))#裁剪   (151,246,844,463)
save_path = "D:/AIRtest/UDun_UI/snapshot/Mnemonic_phrase.png"#保存路径
imwrite(save_path, sna)  # 保存图片到文件

#图像预处理函数
def preprocess_image(img_path):
    img = cv2.imread(img_path)
    # 灰度化
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    # 去噪(雾化)
    denoised = cv2.GaussianBlur(gray, (3, 3), 0)
    # 高对比度锐化
    # sharpened = cv2.addWeighted(gray, 1.5, denoised, -0.5, 0)
    # 二值化,   cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY 文字为白色，背景为黑色
    thresh = cv2.adaptiveThreshold(denoised, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 2)
    # 返回二值化后的图像
    return thresh
    # img = cv2.imread(img_path)
    # #灰度化（第一步：简化图像，为后续处理打基础）
    # gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    # #高斯模糊（第二步：先去噪，避免噪点干扰后续操作） 雾化
    # blur = cv2.GaussianBlur(gray, (5, 5), 0)  # 去除细微噪点
    # #锐化（第三步：在去噪后增强边缘，避免模糊过度）
    # sharpened = cv2.addWeighted(gray, 1.5, blur, -0.5, 0)  # 高对比度锐化
    # #二值化（第四步：将灰度图转为黑白，分离文字与背景）
    # # 注意：cv2.threshold返回两个值（阈值, 处理后图像），需取第二个值
    # _, binary = cv2.threshold(sharpened, 127, 255, cv2.THRESH_BINARY)  # 修正：添加阈值返回值接收
    # #腐蚀（第五步：去除二值化后的边缘毛刺）
    # kernel = np.ones((1, 1), np.uint8)
    # eroded = cv2.erode(binary, kernel, iterations=1)  # 修正：输入应为二值化图像
    # #膨胀（第六步：强化字符轮廓，连接断裂笔画）
    # kernel = np.array([[1, 1, 1]], dtype=np.uint8)
    # dilated = cv2.dilate(eroded, kernel, iterations=1)
    # return sharpened

# 使用Tesseract识别图片文字
def tesseract_ocr(img_path):
    # 打开图片
    sna = preprocess_image(img_path)
    # 识别文字（lang="chi_sim"表示简体中文，"eng"表示英文）
    text = pytesseract.image_to_string(sna, lang="eng")
    return text.strip()


# save_path = "D:/AIRtest/UDun_UI/snapshot/Mnemonic_phrase.png"#保存路径
# save_path = "D:/AIRtest/UDun_UI/snapshot/img_v3_02rn_43e87b30-771e-4478-84e7-0c010d9b4bhu.jpg"

processed = preprocess_image(save_path)
processed_path1 = "D:/AIRtest/UDun_UI/snapshot/1.png"#保存路径
imwrite(processed_path1, processed)
content = tesseract_ocr(save_path)
print(content)
